package com.proj.hot.login;

import android.os.Handler;
import android.util.Log;

import com.proj.hot.GlobalParams;
import com.proj.hot.utils.DebugUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * apk登录认证工具
 */
public class DataManager {

    private final static String TAG = "yyst_login";
    private static HashMap<String, String> loginMap = new HashMap<String, String>();
    private static String loginFlag = "no_value";
//    private final static String BASEURL = "http://119.29.85.209:3000/cmovie/login";
    private final static String BASEURL = "http://weixin.coolimax.com:3000/cmovie/login";
    private static OkHttpClient client;
    private static String result;


    private static Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg != null && !msg.equals("")) {
                return;
            }
        }

        ;
    };

    public static void getlogin(String mac, String sn, String terminalManu,
                                String channel, String password, String mark, String appVersion,final LoginResultCallBack loginResultCallBack) {
        DebugUtil.i(TAG, "开始执行apk登录认证......");
        try {

            client = new OkHttpClient.Builder()
                    .connectTimeout(10, TimeUnit.SECONDS)
                    .readTimeout(10, TimeUnit.SECONDS).build();

            RequestBody requestBodyPost = new FormBody.Builder()
                    .add("Mac", mac).add("Sn", sn)
                    .add("TerminalManu", terminalManu).add("Channel", channel)
                    .add("Password", password)
                    .add("Mark", mark)
                    .add("AppVersion", appVersion)
                    .build();

            Request requestPost = new Request.Builder().url(BASEURL)
                    .post(requestBodyPost).build();

            client.newCall(requestPost).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.i(TAG, "调用请求失败了----onFailure()");
                    e.printStackTrace();
                    handler.post(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            loginResultCallBack.onErrorCallBack("onFailure()");
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response)
                        throws IOException {
//					<Response>
//					<FeeMode>1</FeeMode>
//					<TerminalId>2</TerminalId>
//					<ExpireTime>2017-08-12 13:47:32</ExpireTime>
//					<Token>408</Token>
//					<Result>990</Result>
//					<Message>认证失败，设备已禁止使用</Message>
//					<IpAddr>192.168.2.100:8000</IpAddr>
//					<HotelId>3</HotelId>
//					</Response>
                    if (!"".equals(response) || null != response) {//判断xml是否为空
                        result = response.body().string();
                        DebugUtil.i(TAG, "认证返回xml=" + result);
                        //读取“result”标签的值
                        loginMap = ReaderXmlTools.parse(result);
                        loginFlag = loginMap.get("Result").toString()
                                .trim();
                        GlobalParams.feeMode = loginMap.get("FeeMode").toString()
                                .trim();
                        GlobalParams.terminalId = loginMap.get("TerminalId").toString()
                                .trim();
                        GlobalParams.loginMsg = loginMap.get("Message").toString()
                                .trim();
                        GlobalParams.hotelAddrUrl = loginMap.get("IpAddr").toString()
                                .trim();
                        GlobalParams.hotellId = loginMap.get("HotelId").toString()
                                .trim();
                        GlobalParams.hotelImg = loginMap.get("HotelImg").toString()
                                .trim();
                        GlobalParams.CsdWX = loginMap.get("CsdWX").toString()
                                .trim();
                        GlobalParams.CsdQQ = loginMap.get("CsdQQ").toString()
                                .trim();
                        GlobalParams.CsdTel = loginMap.get("CsdTEL").toString()
                                .trim();
                        //转化
//                        if (GlobalParams.feeMode.equals("1")) {
//                            GlobalParams.user_paytype = "0";
//                        } else if (GlobalParams.feeMode.equals("2")) {
//                            GlobalParams.user_paytype = "1";
//                        } else {
//                            GlobalParams.user_paytype = GlobalParams.feeMode;
//                        }

                        if (!"".equals(loginFlag) && null != loginFlag) {
                            handler.post(new Runnable() {//如果result有值
                                @Override
                                public void run() {
                                    loginResultCallBack.onResultCallBack(loginFlag);
                                    DebugUtil.i(TAG, "认证返回loginFlag=" + loginFlag);
                                }
                            });

                        } else {//如果result没有值 传000
                            handler.post(new Runnable() {//如果result有值
                                @Override
                                public void run() {
                                    loginResultCallBack.onResultCallBack("000");
                                    DebugUtil.i(TAG, "认证返回loginFlag=" + loginFlag);
                                }
                            });

                        }

                    } else {//如果为空 给launch抛出000
                        DebugUtil.i(TAG, "认证返回xml为空!给launch抛出000");
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                // TODO Auto-generated method stub
                                loginResultCallBack.onResultCallBack("000");
                                DebugUtil.i(TAG, "认证返回xml为空！");
                                return;
                            }
                        });
                    }


                }
            });
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            handler.post(new Runnable() {
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    DebugUtil.i(TAG, "Exception------认证出现异常！捕获");
                    loginResultCallBack.onResultCallBack("000");
                }
            });
        }
    }
}
